package com.hzjh.base.frame.fragment

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.hzjh.base.frame.BaseViewModel
import com.hzjh.base.frame.mvvm.ViewModelFactory
import java.lang.reflect.ParameterizedType

abstract class AbsVMFragment<VM : BaseViewModel> : AbsFragment() {

    protected lateinit var viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createViewModel(savedInstanceState)
    }


    //反射获取ViewModel实例
    private fun createViewModel(savedInstanceState: Bundle?) {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[1]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            viewModel = ViewModelProvider(
                this.viewModelStore,
                ViewModelFactory(this, savedInstanceState)
            )[tClass] as VM
        }
        viewModel.viewBaseLD.observe(this) {
            if (it == BaseViewModel.POP_OWNER) {
                popSelf()
            }
        }
    }
}